package com.cqie.hospitalescort.service.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqie.hospitalescort.entity.EscortInfo;
import com.cqie.hospitalescort.entity.MedOrder;
import com.cqie.hospitalescort.enums.StatusEnum;
import com.cqie.hospitalescort.mapper.EscortInfoMapper;
import com.cqie.hospitalescort.mapper.MedOrderMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定时任务
 * @author 小伊
 */
@Service
public class ScheduledTaskServiceImpl implements ScheduledTaskService {

    private final Map<String, Timer> paymentCheckTimers = new ConcurrentHashMap<>();

    @Autowired
    private MedOrderMapper medOrderMapper;
    @Autowired
    private EscortInfoMapper escortInfoMapper;


    /**
     * 开启30分钟支付状态检查
     *
     * @param orderCode 订单编号
     * @param delay 时间
     */
    @Override
    @Transactional
    public void schedulePaymentCheck(String orderCode, long delay) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                checkPayment(orderCode);
            }
        }, delay);
        paymentCheckTimers.put(orderCode, timer);
    }

    /**
     * 查看订单状态
     *
     * @param orderCode 订单编号
     */
    private void checkPayment(String orderCode) {
        MedOrder order = medOrderMapper.selectOne(new QueryWrapper<MedOrder>().eq("order_code", orderCode));
        if (order != null && order.getOrderStatus() == 2) { // 如果订单仍然是待支付状态
            order.setOrderStatus(6); // 已取消
            medOrderMapper.updateById(order);
        }
    }

    /**
     * 取消30分钟自动检查支付状态
     *
     * @param orderCode 订单编号
     */
    public void cancelPaymentCheck(String orderCode) {
        Timer timer = paymentCheckTimers.remove(orderCode);
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 定时任务，定时查询待服务订单
     *
     */
    @Override
    @Transactional
    @Scheduled(cron = "0 0/1 * * * ?") //每1分钟执行一次
    public void scheduleOrderCheck() {
        //查询待服务的订单
        List<MedOrder> medOrders = medOrderMapper.selectList(
                new LambdaQueryWrapper<MedOrder>().eq(MedOrder::getOrderStatus, 3));

        if (CollectionUtils.isEmpty(medOrders)) return;

        for (MedOrder medOrder : medOrders) {
            //判断是否已经到达服务时间
            if (medOrder.getOrderStartTime().getTime() <= System.currentTimeMillis()) {
                //更新订单状态为服务中
                medOrder.setOrderStatus(4);
                medOrderMapper.updateById(medOrder);
            }
        }
    }
    /**
     * 定时任务，定时查询服务中订单
     *
     */
    @Override
    @Transactional
    @Scheduled(cron = "0 0/1 * * * ?") //每1分钟执行一次
    public void scheduleOrderIngCheck() {
        //查询服务中的订单
        List<MedOrder> medOrders = medOrderMapper.selectList(
                new LambdaQueryWrapper<MedOrder>().eq(MedOrder::getOrderStatus, 4));

        if (CollectionUtils.isEmpty(medOrders)) return;

        for (MedOrder medOrder : medOrders) {
            //判断是否已经到达服务时间
            if (medOrder.getOrderEndTime().getTime() <= System.currentTimeMillis()) {
                //更新订单状态为已完成
                medOrder.setOrderStatus(5);
                medOrderMapper.updateById(medOrder);

                EscortInfo escortInfo = escortInfoMapper.selectById(medOrder.getEscortId());
                escortInfo.setScore(escortInfo.getScore() + 1);
                escortInfoMapper.updateById(escortInfo);
            }
        }
    }
}
